import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class SetupAdminUser {
    private static final String HOST = "db.test1.wcsbapp.com";
    private static final int PORT = 3306;
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "0YvoGUzwhumnf2KGQvjN";
    private static final String DATABASE_NAME = "ChainUp";

    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String connectionUrl = String.format("jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%%2B8", 
                HOST, PORT, DATABASE_NAME);
            
            System.out.println("连接到ChainUp数据库...");
            
            try (Connection connection = DriverManager.getConnection(connectionUrl, USERNAME, PASSWORD)) {
                
                // 检查是否已有admin用户
                System.out.println("检查现有用户...");
                String checkUserSql = "SELECT user_id, user_name, nick_name, status, password FROM sys_user WHERE user_name = 'admin'";
                try (PreparedStatement checkStmt = connection.prepareStatement(checkUserSql)) {
                    ResultSet rs = checkStmt.executeQuery();
                    
                    if (rs.next()) {
                        System.out.println("找到admin用户:");
                        System.out.println("  用户ID: " + rs.getLong("user_id"));
                        System.out.println("  用户名: " + rs.getString("user_name"));
                        System.out.println("  昵称: " + rs.getString("nick_name"));
                        System.out.println("  状态: " + rs.getString("status"));
                        System.out.println("  密码哈希: " + rs.getString("password"));
                        
                        // 更新admin用户密码为 admin123
                        String newPassword = encryptPassword("admin123");
                        String updateSql = "UPDATE sys_user SET password = ? WHERE user_name = 'admin'";
                        try (PreparedStatement updateStmt = connection.prepareStatement(updateSql)) {
                            updateStmt.setString(1, newPassword);
                            int rowsUpdated = updateStmt.executeUpdate();
                            if (rowsUpdated > 0) {
                                System.out.println("✓ admin用户密码已更新为: admin123");
                            }
                        }
                    } else {
                        System.out.println("未找到admin用户，正在创建...");
                        
                        // 创建admin用户
                        String insertSql = "INSERT INTO sys_user (user_id, dept_id, user_name, nick_name, user_type, email, phonenumber, sex, avatar, password, status, del_flag, login_ip, login_date, create_by, create_time, update_by, update_time, remark) VALUES (1, 103, 'admin', '管理员', '00', 'admin@chainup.com', '15888888888', '1', '', ?, '0', '0', '127.0.0.1', now(), 'admin', now(), '', now(), '管理员')";
                        
                        String adminPassword = encryptPassword("admin123");
                        try (PreparedStatement insertStmt = connection.prepareStatement(insertSql)) {
                            insertStmt.setString(1, adminPassword);
                            int rowsInserted = insertStmt.executeUpdate();
                            if (rowsInserted > 0) {
                                System.out.println("✓ admin用户创建成功");
                                System.out.println("  用户名: admin");
                                System.out.println("  密码: admin123");
                            }
                        }
                        
                        // 添加admin用户角色关联
                        String insertUserRoleSql = "INSERT IGNORE INTO sys_user_role (user_id, role_id) VALUES (1, 1)";
                        try (PreparedStatement insertUserRoleStmt = connection.prepareStatement(insertUserRoleSql)) {
                            insertUserRoleStmt.executeUpdate();
                            System.out.println("✓ admin用户角色关联已设置");
                        }
                        
                        // 添加admin用户岗位关联
                        String insertUserPostSql = "INSERT IGNORE INTO sys_user_post (user_id, post_id) VALUES (1, 1)";
                        try (PreparedStatement insertUserPostStmt = connection.prepareStatement(insertUserPostSql)) {
                            insertUserPostStmt.executeUpdate();
                            System.out.println("✓ admin用户岗位关联已设置");
                        }
                    }
                }
                
                // 验证最终结果
                System.out.println("\n验证admin用户信息:");
                try (PreparedStatement finalCheckStmt = connection.prepareStatement(checkUserSql)) {
                    ResultSet rs = finalCheckStmt.executeQuery();
                    if (rs.next()) {
                        System.out.println("  ✓ 用户名: " + rs.getString("user_name"));
                        System.out.println("  ✓ 昵称: " + rs.getString("nick_name"));
                        System.out.println("  ✓ 状态: " + ("0".equals(rs.getString("status")) ? "正常" : "停用"));
                        System.out.println("  ✓ 密码已设置 (长度: " + rs.getString("password").length() + ")");
                    }
                }
                
                System.out.println("\n===== 管理员账号设置完成 =====");
                System.out.println("登录地址: http://localhost:1024/");
                System.out.println("用户名: admin");
                System.out.println("密码: admin123");
                System.out.println("============================");
                
            } catch (Exception e) {
                System.err.println("数据库操作失败: " + e.getMessage());
                e.printStackTrace();
            }
            
        } catch (Exception e) {
            System.err.println("连接失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 密码加密方法 (MD5加密，与RuoYi框架保持一致)
    private static String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不可用", e);
        }
    }
}